package com.rtx.wms.customer.grp.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rtx.api.annotation.DataSourceAnnotation;
import com.rtx.edi.model.api.bo.ApiMappingInfoBo;
import com.rtx.wms.std.common.bean.Codelkup;
import com.rtx.wms.std.common.bean.WmsConstant;
import com.rtx.wms.std.ctclass.ClassHolder;
import com.rtx.wms.std.so.bean.ApiOrders;
import com.rtx.wms.std.so.bean.ApiOrdersCancel;
import com.rtx.wms.std.so.bean.Orderdetail;
import com.rtx.wms.std.so.bean.Orders;
import com.rtx.wms.std.so.bean.Pickdetail;
import com.rtx.wms.std.so.mapper.ApiCancleMapper;
import com.rtx.wms.std.so.mapper.ApiOrdersMapper;
import com.rtx.wms.std.so.mapper.OrderdetailMapper;
import com.rtx.wms.std.so.mapper.OrdersMapper;
import com.rtx.wms.std.so.mapper.dymapper.DyOrderdetailMapper;
import com.rtx.wms.std.so.mapper.dymapper.DyOrdersMapper;
import com.rtx.wms.std.so.service.ApiOrdersService;
import com.rtx.wms.std.so.service.OrdersService;
import com.rtx.wms.std.so.service.PickdetailService;
import com.rtx.wms.std.validation.so.OrdersValidation;

@Primary
@Service
public class GrpOrdersServiceImpl implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderdetailMapper orderdetailMapper;
    
    @Autowired
    protected OrdersValidation ordersValidation;
    
    @Autowired
    ApiOrdersService apiOrdersService;
    
    @Autowired
    ApiOrdersMapper apiOrdersMapper;
    
    @Autowired
    ApiCancleMapper apiCancleMapper;
    
    @Autowired
    PickdetailService pickdetailService;
    
    @Autowired
    DyOrdersMapper dyOrdersMapper;
    
    @Autowired
    DyOrderdetailMapper dyOrderdetailMapper;
    
    

    @DataSourceAnnotation
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addOrders(String whseid, Orders orders,ApiMappingInfoBo config) {
    	LambdaQueryWrapper<ApiOrders> query = Wrappers.lambdaQuery();
    	query.eq(ApiOrders::getExternorderkey, orders.getExternorderkey());
    	query.eq(ApiOrders::getEdiflag, "PC");
    	boolean cancleflag = apiOrdersMapper.exists(query);
    	if(cancleflag) {
    		orders.setStatus("98");
    		orders.setCancelmark("98");
    		orders.getDetails().stream().forEach(entity->{entity.setStatus("98");});
    	}
    	
        //是否使用 动态加载字段拼接sql
        boolean activeConfig = false;
        //获取生效的目标apiid，就是当前需要被调用的restapi
        Long targetid = config.getTargetApi().getId();
        //获取启动或者被被更新时候动态创建的实体类
        Map<String,Class> map = ClassHolder.apiconfigClassMap.get(targetid+"");
        //假如动态创建的类存在则 通过调用通过反射获取bean对象属性拼接sql的方法
        if(map != null) {
        	activeConfig = true;
        }
    	
    	if(activeConfig) {
    		dyOrdersMapper.rtxconfigColumnsSave(orders);
    		for(Orderdetail od : orders.getDetails()){
    			dyOrderdetailMapper.rtxconfigColumnsSave(od);
    		}
    	}else {
            ordersMapper.insert(orders);
            for(Orderdetail od : orders.getDetails()){
                orderdetailMapper.insert(od);
            }
    	}
    }

    @DataSourceAnnotation
    @Override
    public List<Orders> selectFinishOrdersByWrapper(String whseid) {
    	List<Orders> allFinishList = new ArrayList<>();
    	
    	LambdaQueryWrapper<Orders> queryWrapper2 = Wrappers.lambdaQuery();
    	queryWrapper2
    	.eq(Orders::getRtxiscontainer, "1")
    	.eq(Orders::getToexamine, "0")
    	.isNotNull(Orders::getExternorderkey)
    	.in(Orders::getEdiflag, WmsConstant.DEFAULT_FLAG,WmsConstant.FAIL_FLAG)
        .eq(Orders::getStatus,"95")
        .lt(Orders::getRtxqueue, 2);
        List<Orders> orderList2 = ordersMapper.selectList(queryWrapper2);
        for(Orders o : orderList2){
            LambdaQueryWrapper<Orderdetail> odqueryWrapper = Wrappers.lambdaQuery();
            odqueryWrapper.eq(Orderdetail::getOrderkey,o.getOrderkey());
            o.setDetails(orderdetailMapper.selectList(odqueryWrapper));
        }
        
        allFinishList.addAll(orderList2);
    	
    	LambdaQueryWrapper<Orders> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper
    	.eq(Orders::getRtxiscontainer, "0")
    	.eq(Orders::getToexamine, "0")
    	.isNotNull(Orders::getExternorderkey)
    	.in(Orders::getEdiflag, WmsConstant.DEFAULT_FLAG,WmsConstant.FAIL_FLAG)
        .gt(Orders::getStatus,54)
        .lt(Orders::getStatus,98)
        .lt(Orders::getRtxqueue, 2);
        List<Orders> orderList = ordersMapper.selectList(queryWrapper);
        
        for(Orders o : orderList){
            LambdaQueryWrapper<Orderdetail> odqueryWrapper = Wrappers.lambdaQuery();
            odqueryWrapper.eq(Orderdetail::getOrderkey,o.getOrderkey());
            List<Orderdetail> odList = orderdetailMapper.selectList(odqueryWrapper);
            
            for(Orderdetail od:odList) {
                QueryWrapper<Pickdetail> pkquery = Wrappers.query();
                pkquery.select("sum(qty) as qty");
                pkquery.eq("orderlinenumber", od.getOrderlinenumber());
                pkquery.eq("orderkey", od.getOrderkey());
                List<Pickdetail> pList = pickdetailService.queryByCondition(whseid, pkquery);
                if(CollectionUtils.isEmpty(pList)) {
                	throw new RuntimeException("出库单-"+od.getOrderkey()+"-"+od.getOrderlinenumber()+"-"+"拣货明细不存在!");
                }
                od.setShippedqty(pList.get(0).getQty());
            }

            
            o.setDetails(odList);
        }
        
        allFinishList.addAll(orderList);
        
        
        return allFinishList;
    }
    
    @DataSourceAnnotation
    @Override
    public List<Orders> selectOrderNotDetailByWrapper(String whseid, Wrapper<Orders> wrapper) {
        return ordersMapper.selectList(wrapper);
    }

    @DataSourceAnnotation
    @Override
    public void updateByWrapper(String whseid, LambdaUpdateWrapper<Orders> wrapper) {
        ordersMapper.update(null,wrapper);
    }
    
    @DataSourceAnnotation
    @Override
	public void updatedetailByWrapper(String whseid, LambdaUpdateWrapper<Orderdetail> wrapper) {
		orderdetailMapper.update(null, wrapper);
	}

	@DataSourceAnnotation
    @Override
    public void handlerExistsOrders(String whseid, String externorderkey) {
        //根据“外部单号”查询ORDERS表中是否存在，如果没有就新建一个WMS出库单。
        LambdaQueryWrapper<Orders> ordersQuery = Wrappers.lambdaQuery();
        ordersQuery.eq(Orders::getExternorderkey,externorderkey);
        List<Orders> ordersList = ordersMapper.selectList(ordersQuery);
        if(!CollectionUtils.isEmpty(ordersList)){
            //否则查看WMS订单状态是否是初始状态（对应ORDERS单状态STATUS>10）
            Orders orders = ordersList.get(0);
            //如果否，则将WMS表头和表明细全部删除后，再插入一个新的WMS出库单；
            //如果是,写入“XXX单据已开始拣货”报错数据到ERRMSG中，不允许改单。
            if(Integer.parseInt(orders.getStatus()) > 9){
                throw new RuntimeException("出库单：" + orders.getExternorderkey() +"已开始拣货，不允许改单");
            }else{
                //根据外部单号删除明细
                LambdaQueryWrapper<Orderdetail> detailQuery = Wrappers.lambdaQuery();
                detailQuery.eq(Orderdetail::getExternorderkey,externorderkey);
                orderdetailMapper.delete(detailQuery);
                //删除表头
                ordersMapper.delete(ordersQuery);
            }
        }
    }


	/**
     * 获取仓库id
     * @param apiOrdersCancel
     * @return
     */
    @DataSourceAnnotation
    public String getwmwhseid(String datssourcekey,ApiOrdersCancel apiOrdersCancel,String customerid) {
    	String storerkey =apiOrdersCancel.getStorerkey();
    	if("rtxwmsprod001".equals(customerid)||"23202400".equals(apiOrdersCancel.getAppkey())) {
    		storerkey = apiOrdersCancel.getWhseid();
    	}else if(Arrays.asList("28428678".split(",")).contains(apiOrdersCancel.getAppkey())) {
    		storerkey = apiOrdersCancel.getWhseid();
    	}else {
    		storerkey = apiOrdersCancel.getWhseid();
    	}
        //获取系统代码【RTXSHIPSTORE】，使用店仓编号匹配代码获取仓库编号、货主编号
        LambdaQueryWrapper<Codelkup> codelkupQuery = Wrappers.lambdaQuery();
        codelkupQuery.eq(Codelkup::getCode, storerkey).eq(Codelkup::getListname, "RTXSHIPSTORE");
        Codelkup rtxshipstore = ordersValidation.validationCodelkup(WmsConstant.ENTERPRISE, codelkupQuery, true);
        return rtxshipstore.getUdf2();
    }
    
    @DataSourceAnnotation
    @Override
    public List<Orders> selectOrdersByWrapper(String whseid, Wrapper<Orders> wrapper) {
        List<Orders> orderList = ordersMapper.selectList(wrapper);
        for(Orders o : orderList){
            LambdaQueryWrapper<Orderdetail> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(Orderdetail::getOrderkey,o.getOrderkey());
            o.setDetails(orderdetailMapper.selectList(queryWrapper));
        }
        return orderList;
    }

}
